from agentDesign.L1.read_map import ReadMap
from flask import Flask, jsonify, request, Response
import sys, os
import json
sys.path.append(
    os.path.abspath(os.path.join(os.path.dirname("__file__"))))
from initmodel.initriders import init_rider
# from L1.read_map import ReadMap

app = Flask(__name__)

# nums = []
# riders_num = 0
# riders_id = []
# riders_ration = []
# riders_money = []
# riders_status = []
rider_id = 0
app.config['id'] = 0
read_map = ReadMap()
app.config['home'] = read_map.get_door("洋房")
if 'home' in app.config:
    app.config['home'].pop(1)
print(app.config['home'])


@app.route('/api/addAgent', methods=['GET', 'POST'])
def addAgent():
    if request.method == 'GET':
        data = {
            'message': 'hello'
        }
        return jsonify(data)
    elif request.method == 'POST':
        data = request.get_json()
        rider_info = {'id': app.config['id']}
        riders_num = int(data["params"]["riders_num"])
        print(riders_num)
        attributes = data["params"]["attribute"]
        for attribute in attributes:
            key_att = attribute['value1']
            value_att = attribute['value2']
            print(key_att, value_att)
            if key_att != 'status':
                value_att = int(value_att)
            rider_info[key_att] = value_att
        for i in range(riders_num):
            init_rider(app.config['id'], rider_info['rationality'], 10 - rider_info['rationality'],
                       rider_info['health'], app.config['home'][int(app.config['id'] % 13)][0],
                       rider_info['money'])
            app.config['id'] += 1

        # for key, item in ans.items():
        #     print(key, item)

        print(rider_info)
        return jsonify({"message": "get message success"})


@app.route('/smartCity/getAlgorithm', methods=['GET'])
def getAlgorithm():
    
    filename = "regulation/algorithm.json"
    with open(filename, 'r') as f:
        data = json.load(f)
    print(data)
    return jsonify({"message": "get message success","data": data})

@app.route('/smartCity/delAlgorithm', methods=['POST'])
def delAlgorithm():
    
    name = request.get_json()['name']
    filename = "regulation/algorithm.json"
    with open(filename, 'r') as f:
        data = json.load(f)
    index = -1
    for i in range(len(data)):
        if data[i]['name'] == name:
            index = i 
    if index >= 0:
        del data[index]
    
    with open(filename, 'w') as f:
        json.dump( data, f)
    return jsonify({"message": "get message success","data": data})


@app.route('/smartCity/addAlgorithm', methods=['POST'])
#@cross_origin(supports_credentials = True)
def addAlgorithm():
 
    # data = request.get_json()
    data = dict(request.form)
    # data['name'] =
    
    if 'file' not in request.files:
        
        return jsonify({'error': '没有上传文件'})
 
    file = request.files['file']
 
    if file.filename == '':
        return jsonify({'error': '没选择文件'})

    print(file)
    print(file.filename)
    filename = file.filename
    file_type = file.filename.split('.')[-1]
    path = 'rules/'+str(data['type']).split(' ')[0]
    if not os.path.exists(path):
        os.makedirs(path) 
    if file_type == 'py':
        file.save(os.path.join(path, str(data['name'])+'.py'))
    else:
        file.save(os.path.join(path, filename))

    fdata = []
    filename = "regulation/algorithm.json"
    if os.path.exists(filename):
        file=open(filename,'r',encoding='utf-8')
        fdata = json.load(file)
    fdata.append(data)
    with open(filename, 'w') as file:
        json.dump(fdata, file)
    print(data)
    return jsonify({"message": "get message success","data": fdata})

@app.route("/smartCity/generateTemplate", methods=['POST'])
def generateTemplate():
    data = request.get_json()
    
    if data['type'] == 'dispatch algorithm':
        PATH = "regulation/template/dispatchTemplate.py"
    elif data['type'] == 'reposition algorithm':
        PATH = "regulation/template/repositionTemplate.py"
    else:
        return jsonify({"message": "error"})
    
    with open(PATH,"rb") as f:
        stream = f.read()
    
    response = Response(stream, content_type = 'application/octet-stream')
    response.headers['Connect-disposition'] = 'attachment; filename=%s' % PATH.split("/")[1]
    return response

@app.route("/", methods=['GET'])
def hello():
    return 'hello world'



if __name__ == '__main__':
    init_members = {"members": []}
    with open('./memories/riders.json', 'w') as file:
        json.dump(init_members, file)
    app.run(host='0.0.0.0', port=9090, debug=True)
